package com.platform.controller;

import com.platform.entity.MaterielEntity;
import com.platform.entity.UserEntity;
import com.platform.service.MaterielService;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import com.platform.utils.excel.ExcelExport;
import com.platform.utils.excel.ExcelImport;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("materiel")
public class MaterielController {
    @Autowired
    private MaterielService materielService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("materiel:list")
    public R list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);

        List<MaterielEntity> orderList = materielService.queryList(query);
        int total = materielService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("materiel:info")
    public R info(@PathVariable("id") Integer id) {
        MaterielEntity materiel = materielService.queryObject(id);
        return R.ok().put("materiel", materiel);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("materiel:save")
    public R save(@RequestBody MaterielEntity materiel) {
        materiel.setIsDelete(0);
        materiel.setIsOnSale(1);
        materielService.save(materiel);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("materiel:update")
    public R update(@RequestBody MaterielEntity materiel) {
        materielService.update(materiel);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("materiel:delete")
    public R delete(@RequestBody Integer[] ids) {
        materielService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     *
     * @param params
     * @return
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {
        List<MaterielEntity> list = materielService.queryList(params);
        return R.ok().put("list", list);
    }

    /**
     * 导入物料
     */
    @RequestMapping("/import")
    /*@RequiresPermissions("materiel:import")*/
    public R export(@RequestParam Map<String, Object> params, HttpServletResponse response,
                    @RequestParam(value="file") MultipartFile file) {
        String name = file.getOriginalFilename();
        //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
        if(name==null || ("").equals(name) && file.getSize()==0) return R.error("空文件不允许导入！");

        //通过解析MultipartFile对象获取excel内容，并且将其拼装为Map<Integer, List<String[]>>对象返回
        //ExcelImport.getExcelDataAll(file);

        //通过解析MultipartFile对象获取excel内容，并且将其拼装为List<String[]>对象返回
        List<String[]> materielList = ExcelImport.getExcelData(file);
        MaterielEntity materiel = new MaterielEntity();
        String[] strs = materielList.get(0);
        int a = 0;
        int b = 1;
        int c = 2;
        int d = 3;
        int e = 4;
        int f = 5;
        int g = 6;
        //物料编码,物料名称,物料类型,单位,图号,供货渠道,品牌
        for (int i = 0; i < strs.length; i++) {
            if (strs[i].equals("物料编码")) {
                a = i;
                break;
            }
        }
        for (int j = 0; j < strs.length; j++) {
            if (strs[j].equals("物料名称")) {
                b = j;
                break;
            }
        }
        for (int k = 0; k < strs.length; k++) {
            if (strs[k].equals("物料类型")) {
                c = k;
                break;
            }
        }
        for (int l = 0; l < strs.length; l++) {
            if (strs[l].equals("单位")) {
                d = l;
                break;
            }
        }
        for (int m = 0; m < strs.length; m++) {
            if (strs[m].equals("图号")) {
                e = m;
                break;
            }
        }
        for (int n = 0; n < strs.length; n++) {
            if (strs[n].equals("供货渠道")) {
                f = n;
                break;
            }
        }
        for (int z = 0; z < strs.length; z++) {
            if (strs[z].equals("品牌")) {
                g = z;
                break;
            }
        }

        Iterator it = materielList.iterator();
        int count = 0;
        while(it.hasNext()){
            count++;
            //把获取到的值强转成字符串数组类型
            strs = (String[]) it.next();
            if(count != 1){
                materiel.setMaterielCode(strs[a]);
                materiel.setMaterielName(strs[b]);
                materiel.setMaterielType(strs[c]);
                materiel.setUnit(strs[d]);
                materiel.setDrawingNumber(strs[e]);
                materiel.setSupplyChannel(strs[f]);
                materiel.setBrand(strs[g]);
                materiel.setIsDelete(0);
                materiel.setIsOnSale(1);
                materiel.setSortOrder(count);
                materielService.save(materiel);
            }
        }
        return R.ok("导入成功!");
    }

    @RequestMapping("/batchImport")
    /*@RequiresPermissions("materiel:batchImport")*/
    public R batchImport(@RequestParam Map<String, Object> params, HttpServletResponse response,
                    @RequestParam(value="filename") MultipartFile file) {
        String Msg = "";
        //判断文件是否为空
        if(file==null) return R.error("文件不存在!");
        //获取文件名
        String name=file.getOriginalFilename();
        //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
        long size=file.getSize();
        if(name==null || ("").equals(name) && size==0) return R.error("文件为空！");

        //批量导入。参数：文件名，文件。
        boolean b = materielService.batchImport(name,file);
        if(b){
            Msg ="批量导入EXCEL成功！";
        }else{
            Msg ="批量导入EXCEL失败！";
            return R.error(Msg);
        }
        return R.ok(Msg);
    }
}
